import ddmpt_pb2_grpc
import ddmpt_pb2
from cmd import Cmd
import grpc
import yaml
import time


class Runtime(ddmpt_pb2_grpc.RuntimeServicer):
    def insertEntry(self, request, context):
        return super().insertEntry(request, context)


class Ddmshell(Cmd):
    prompt = 'ddmshell> '
    stubs = {}

    def do_dump(self):
        """dd"""
        print('dump')

    def do_connect_all(self, line):
        with open(line) as f:
            parsed = yaml.safe_load(f)
            for ele in parsed['ddmdConfs']:
                c = grpc.insecure_channel('localhost:%d' % ele['port'])
                self.stubs[ele['name']] = ddmpt_pb2_grpc.RuntimeStub(c)

    def do_connect(self, line):
        print(line)
        channel = grpc.insecure_channel(line)
        self.stub = ddmpt_pb2_grpc.RuntimeStub(channel)

    def do_deploy(self, line):
        with open(line) as f:
            parsed = yaml.safe_load(f)
            for conf in parsed['vnodeConfs']:
                nexthops = []
                for dc in conf['downstreamConfs']:
                    nexthop = ddmpt_pb2.Nexthop(
                        vid=dc['vid'], device=dc['device'], via=dc['via'], addr=dc['addr'])
                    nexthops.append(nexthop)
                entry = ddmpt_pb2.Entry(vid=conf['vid'], nexthops=nexthops)
                self.stubs[conf['device']].insertEntry(entry)

    def do_insert_entry(self, line):
        print(line)
        nexthops = [ddmpt_pb2.Nexthop(device="aaa", vid=2)]
        entry = ddmpt_pb2.Entry(vid=1, nexthops=nexthops)
        self.stubs[line].insertEntry(entry)

    def do_show_vroutes(self, line):
        resp = self.stubs[line].showVroutes(ddmpt_pb2.Empty())
        print(resp)

    def do_verify(self, line):
        ip, prefix, src, vid = line.split()
        task = ddmpt_pb2.VerifyTask(ip=int(ip), prefix=int(prefix), vid=int(vid))
        print(time.time())
        self.stubs[src].verify(task)


    def do_exit(self, line):
        exit(0)


sh = Ddmshell(completekey='tab').cmdloop()
